package org.github.core.spring.restful;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.annotation.Nullable;
import javax.validation.constraints.NotNull;
import org.springframework.http.HttpStatus;

import static cn.hutool.core.text.CharSequenceUtil.firstNonBlank;
import static org.github.core.Const.SUB_CODE_DEFAULT;
import static org.github.core.util.JacksonUtil.json;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
import static org.springframework.http.HttpStatus.OK;

/**
 * JSON of basic.
 *
 * @author JYD_XL
 * @see java.io.Serializable
 * @see java.util.function.Supplier
 */
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Base {
    /** 状态 */
    private int code = OK.value();
    /** 错误码 */
    private int subCode = SUB_CODE_DEFAULT;
    /** 信息 */
    @NotNull
    private String msg = OK.name();

    /**
     * Generator.
     */
    @NotNull
    public static Base error() {
        return of(INTERNAL_SERVER_ERROR, null);
    }

    /**
     * Generator.
     */
    @NotNull
    public static Base ok() {
        return of(OK, null);
    }

    /**
     * Generator.
     */
    @NotNull
    public static Base of(HttpStatus status, @Nullable String msg) {
        return of(status, SUB_CODE_DEFAULT, msg);
    }

    /**
     * Generator.
     */
    @NotNull
    public static Base of(HttpStatus status, int subCode, @Nullable String msg) {
        return new Base(status.value(), subCode, firstNonBlank(msg, status.name()));
    }

    @Override
    public String toString() {
        return json(this);
    }

    public void setCode(int code) {
        this.code = code;
    }

    public boolean failure() {
        return !success();
    }

    public boolean success() {
        return code == OK.value();
    }
}
